<template>
	<view class="contract">
		<!-- 自定义导航栏 -->
		<view :style="{ height: navBarHeight + 'px' }" class="custom-nav-bar">
			<view class="nav-back" @click="goBack"><u-icon name="arrow-left" color="#303133" size="24"></u-icon></view>
			<view class="nav-title">合同审查</view>
		</view>
		<!-- 页面主体内容 -->
		<view class="main">
			<view class="cardBox">
				<view class="ImageBox">
					<image v-if="checkInclude(fileArr[0],fileEnd)" style="width: 80rpx;height:80rpx;position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);" src="@/static/file.png" mode="aspectFit"></image>
					<image v-else :src="fileArr[0]" mode="aspectFill"></image>
					<view class="ImgNumber">共{{fileArr.length}}张</view>
				</view>
				<view class="text">{{name}}</view>
			</view>
			
			<view class="formBox">
				<!-- <view class="label"><label>*</label> 请选择合同类型</view> -->
				<view style="margin-bottom: 30rpx;">
					<up-select v-model:current="form.chatType" label="请选择合同类型" :options="chatConfigList" @select="selectItem" keyName='aiChatId' labelName="chatType"></up-select>
				</view>
				<view style="margin-bottom: 60rpx;">
					  <up-input placeholder="请输入内容" border="surround" v-model="form.chatType" disabled="true"></up-input>
				</view>
				
				<view class="label" style="margin-bottom: 30rpx;"><label>*</label> 自设审核要求</view>
				<view class="">
					<up-textarea v-model="form.demand" placeholder="请输入内容" ></up-textarea>
				</view>
			</view>
		</view>
		
		<view class="bottom">
			<view class="" @click="goBack()"><u-button type="success" :plain="true" text="上一步"></u-button></view>
			<view class="" @click="sureSub()"><u-button type="primary" text="确认送审"></u-button></view>
		</view>
	</view>
	
		<up-popup :show="showSubLoader" :round="20" mode="bottom">
			<view class="loaderBox">
				<!-- 合同文件上传 -->	
				<view class="item" v-if="fileshow">
					<view class=""><up-loading-icon :show='fileshow' color='#409EFF'></up-loading-icon></view>
					<view class="">合同文件文件上传中，请稍后...</view>
				</view>
				<view class="item" v-else>
					<view class=""><up-icon name="checkbox-mark" color='#409EFF'></up-icon></view>
					<view class="">合同文件上传已结束， <label class="errorColor" style="margin-right: 30rpx;">失败：{{ failFiles }}</label><label class="successColor">成功：{{ successFiles }}</label> </view>
				</view>
				
				<!-- 合同分析任务创建 -->
				<view class="item" v-if="createdshow">
					<view class=""><up-loading-icon :show='createdshow' color='#409EFF'></up-loading-icon></view>
					<view class="">合同分析任务创建中，请稍后...</view>
				</view>
				<view class="item" v-else>
					<view class=""><up-icon name="checkbox-mark" color='#409EFF'></up-icon></view>
					<view class="">合同分析任务创建成功。</view>
				</view>
				
				<!-- 合同分析中 -->
				<view class="item" v-if="analysisshow">
					<view class=""><up-loading-icon :show='analysisshow' color='#409EFF'></up-loading-icon></view>
					<view class="">合同分析中，请稍后...</view>
				</view>
				<view class="item" v-else>
					<view v-if="taskStatus==3" class=""><up-icon name="error-circle-fill" color='#fa3534'></up-icon></view>
					<view v-else class=""><up-icon name="checkbox-mark" color='#409EFF'></up-icon></view>
					<view class="">合同分析已完成。 <label v-if="taskStatus==3" class="errorColor" style="margin-right: 30rpx;">失败</label><label v-else class="successColor">成功</label></view>
				</view>
				
				<!-- 合同陷阱标识 -->
				<view class="item" v-if="signshow">
					<view class=""><up-loading-icon :show='signshow' color='#409EFF'></up-loading-icon></view>
					<view class="">合同陷阱标识中，请稍后...</view>
				</view>
				<view class="item" v-else>
					<view v-if="taskStatus==3" class=""><up-icon name="error-circle-fill" color='#fa3534'></up-icon></view>
					<view v-else class=""><up-icon name="checkbox-mark" color='#409EFF'></up-icon></view>
					<view class="">合同陷阱标识完成。</view>
				</view>
				
				<view class="bottom">
					<view class="" v-if="fileshow || createdshow || analysisshow || signshow">
						<view class="" @click="goHome()"><u-button type="primary" text="稍后查看"></u-button></view>
					</view>
					<view v-else style="display: flex;justify-content: space-around;gap: 20rpx;">
						<view class="" @click="golist()"><u-button type="default" :plain="true" text="前往列表"></u-button></view>
						<view class="" @click="goInfo()"><u-button type="primary" text="查看详情"></u-button></view>
					</view>
				</view>
			</view>
		</up-popup>
</template>

<script setup>
	import { ref, onMounted, reactive } from 'vue';
	import { listChatConfig, sendMessageContent,detImageFile,listChatConfigInfo,listChatConfigImageInfo } from '@/api/index.js'
	import { getAiAskList, detContractTask } from '@/api/list.js';
	import env from '@/env.js'
	import { getToken, globalHeaders } from '@/utils/auth';
	import { useAuthStore } from '@/store/index';
	import { onReady, onLoad,onHide } from '@dcloudio/uni-app' // 新增引入

	const authStore = useAuthStore();
	// 自定义导航栏的高度
	const navBarHeight = ref(0);
	const form = ref({aiChatId:'',chatType:'',content:'',demand:''})	
	const showSubLoader = ref(false)
	const fileshow = ref(true)
	const createdshow = ref(true)
	const analysisshow = ref(true)
	const signshow = ref(true)
	
	const chatConfigList = ref()
	const fileArr = ref([])
	const name = ref('')
	const fileUrls = ref([])
	
	const successFiles = ref(0)
	const failFiles = ref(0)
	const taskId = ref('')
	const taskStatus = ref(0)
	
	const queryParams = ref({
		pageNum: 1,
		pageSize: 1,
		userId: authStore.userId
	})
	const fileEnd = ref(['.doc','.docx','.pdf'])
	const timer = ref(null);
	
	// 返回上一页的方法
	const goBack = () => {
	    uni.navigateBack();
	};
	
	// 获取类别
	const getChatConfigList = async () => {
		const res = await listChatConfig();
		if (res.data.code === 200) {
			chatConfigList.value = res.data.rows;
			console.log(chatConfigList.value)
			form.value = res.data.rows[0];
		}
	};

	const selectItem = (e) => {
		console.log(e)
		form.value = e
	}
	
	const sureSub = async () => {
		showSubLoader.value = true
		fileshow.value = true
		createdshow.value = true
		analysisshow.value = true
		signshow.value = true
		taskId.value = ''
		upLoadFiles(fileArr.value, (results) => {
		  console.log("最终结果:", results);
		  fileshow.value = false
		  if(fileUrls.value.length == results.length) {
			  submitCotent(); // 全部完成后执行下一步
		  }
		});
	}
	
	const upLoadFiles = (files, nextStep, index = 0, results = []) => {
		// 所有文件处理完毕时调用 nextStep
		if (index >= files.length) {
			console.log("所有文件上传完成（含失败项）", results);
			nextStep(results); // 传入汇总结果
			return;
		}
		const file = files[index];
		console.log(`正在上传第 ${index + 1}/${files.length} 个文件: ${file}`);
		
		uni.uploadFile({
			url: `${env.baseURL}/resource/oss/upload/compress`, //仅为示例，非真实的接口地址
			header: globalHeaders(),
			filePath: file,
			name: 'file',
			formData: {
				'chatType': form.value.chatType
			},
			success: (uploadFileRes) => {
				let res = JSON.parse(uploadFileRes.data)
				if (res.code === 200) {
					results.push({ status: "success", data: res.data });
					successFiles.value =  successFiles.value + 1
					fileUrls.value.push(res.data)
					upLoadFiles(files, nextStep, index + 1, results);
				} else {
				  results.push({ status: "failed", error: res.msg });
				  failFiles.value =  failFiles.value + 1
				  // 即使失败也继续下一个文件
				  upLoadFiles(files, nextStep, index + 1, results);
				}
			}
		});
	}
	
	const submitCotent = async () => {
		const newArr = fileUrls.value
		  .map((item) => {
				return item.url;
		  })
		  .filter((item) => item !== null); // 过滤掉 null 值
		  
		  let currentDate = new Date();
		  // let year = currentDate.getFullYear();
		  let month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
		  let day = String(currentDate.getDate()).padStart(2, '0'); // 补零
		  let hours = String(currentDate.getHours()).padStart(2, '0'); // 补零
		  let minutes = String(currentDate.getMinutes()).padStart(2, '0'); // 补零
		  let seconds = String(currentDate.getSeconds()).padStart(2, '0'); // 补零
		   
		let data = {
		  chatType: '',
		  content: '',
		  fileUrls: [],
		  sessionKey: authStore.userId,
		  topic: 'contentWebSocket',
		  taskNumber:`${month}月${day}日 ${hours}:${minutes}:${seconds}`
		};
		data.chatType = form.value.chatType;
		data.content = form.value.content;
		data.fileUrls = newArr;
		await sendMessageContent(data);
		setTimeout(() => {
			createdshow.value = false
			getList()
		}, 1000);
		
	};
	
	const getList = async () => {
		const res = await getAiAskList(queryParams.value)
		if(res.data.code === 200) {
			if(taskId.value=='')taskId.value = res.data.rows[0].taskId
			console.log(taskId.value)
			taskStatus.value = res.data.rows[0].taskStatus
			if(res.data.rows[0].taskStatus != 2 && res.data.rows[0].taskStatus != 3) {
				timer.value = setTimeout(() => {
					analysisshow.value = true
					getList()
				}, 2000);
			}else if(res.data.rows[0].taskStatus == 2){
				analysisshow.value = false
				getImage(taskId.value)
			}else if(res.data.rows[0].taskStatus == 3){
				analysisshow.value = true
			}
		}
	}
	
	const getImage = async (taskId) => {
		const res = await listChatConfigImageInfo(taskId)
		console.log(res.data.rows)
		if(res.data.code === 200) {
			if(res.data.rows.length == 0) {
				setTimeout(() => {
					signshow.value = true
					getImage(taskId)
				}, 2000);
			}else {
				signshow.value = false
			}
		}
	}
	
	const goHome = () => {
		clearTimeout(timer.value)
		uni.switchTab({
			url:'/pages/home/index'
		});
	}
	
	const golist = () => {
		uni.switchTab({
			url:'/pages/list/index'
		});
	}
	
	const goInfo = () => {
		uni.redirectTo({
		    url: `/pages/index/index?taskId=${taskId.value}`
		});
	}
	
	const checkInclude = (str,arr) => {
		 return [...arr].some(element => str.includes(element));
	}
	
	onLoad(async (options) => {
		await getChatConfigList()
		if(options.fileArr){
			fileArr.value = JSON.parse(options.fileArr)
			let arr = fileArr.value[0].split('/')
			console.log(arr)
			name.value = arr[arr.length - 1]
		}
	})

	onHide(()=> {
		clearTimeout(timer.value)
	})
	
	onMounted(async () => {
	    try {
	        const res = await uni.getSystemInfo();
	        // 获取状态栏高度（刘海高度）
	        const statusBarHeight = res.statusBarHeight;
	        // 标准导航栏高度，一般为 44px（iOS）或 48px（Android）
	        const defaultNavBarHeight = res.platform === 'ios' ? 44 : 48;
	        // 计算自定义导航栏的高度
	        navBarHeight.value = statusBarHeight + defaultNavBarHeight;
			
			authStore.userId = uni.getStorageSync('loginInfo').user.userId
	    } catch (error) {
	        console.error('获取设备信息失败:', error);
	    }
	});
</script>

<style>
	.contract {
		background-color: #f0f4f9;
		display: flex;
		flex-direction: column;
		background-color: #fff;
	}
	.custom-nav-bar {
		position: relative;
		top: 0;
		width: 100vw;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #F2F3F5;
		z-index: 99;
	}
	
	.nav-title {
	    font-size: 40rpx;
	    font-weight: bold;
		text-align: center;
		position: absolute;
		bottom: 20rpx;
	}
	.nav-back{
		font-weight: bold;
		position: absolute;
		bottom: 20rpx;
		left:	20rpx
	}
	.main {
		width: 100vw;
		padding: 20rpx;
		box-sizing: border-box;
		display: flex;
		flex-wrap: wrap;
		gap: 30rpx;
		padding-bottom: 100rpx;
	}
	.main .cardBox{
		display: flex;
		gap: 30rpx;
		width: 100%;
	}
	.main .cardBox .ImageBox {
		width: 200rpx;
		height: 200rpx;
		border-radius: 20rpx;
		overflow: hidden;
		position: relative;
	}
	.main .cardBox .ImageBox .ImgNumber {
		position: absolute;
		bottom: 20rpx;
		right: 20rpx;
		background-color: rgba(0, 0, 0, .4);
		color: #fff;
		border-radius: 6rpx;
		padding: 6rpx;
		font-size: 24rpx;
	}
	.main .cardBox .text {
		width: calc(100vw - 300rpx);
		display: flex;
		align-items: center;
		word-break: break-all;
	}
	.main .formBox {
		width: 100%;
	}
	.main .formBox .label {
		color: #000;
		font-size: 40rpx;
	}
	.main .formBox .label label {
		color:#fa3534;
		margin-right: 20rpx;
	}
	.main .formBox .u-select__content .u-select__label{
		color: #000;
		font-size: 40rpx;
		display: flex;
		justify-content: left;
	}
	.main .formBox .u-select__content .u-select__label:before {
		content: '*';
		color:#fa3534;
		margin-right: 20rpx;
	}
	.main .formBox .u-select__content .u-select__label .u-select__text {
		    flex: 1;
	}
	.main .formBox .u-select__options__wrap {
		    top: 60rpx !important;
	}
	.bottom {
		margin: 0 20rpx;
		position: fixed;
		bottom: 60rpx;
		left: 0;
		width: calc(100vw - 40rpx);
		display: flex;
		justify-content: space-around;
		gap: 20rpx;
	}
	.bottom view {
		flex: 1;
	}
	.loaderBox {
		width: 100vw;
		height: 30vh;
		padding: 60rpx 40rpx;
		box-sizing: border-box;
	}
	.loaderBox .item {
		display: flex;
		justify-content: start;
		gap: 30rpx;
		align-items: center;
		margin-bottom: 40rpx;
	}
	.errorColor {
		color: #fa3534;
	}
	.successColor {
		color: #67c23a;
	}
</style>